package model

import (
	"time"
	"gorm.io/gorm"
)

type User struct {
	Id         int64     `json:"id" gorm:"primaryKey;autoIncrement"`
	Username   string    `json:"username" gorm:"uniqueIndex;size:50"`
	Password   string    `json:"-" gorm:"size:255"`
	Name       string    `json:"name" gorm:"size:100;not null"`
	Role       string    `json:"role" gorm:"type:enum('user','admin');default:'user'"`
	Phone      string    `json:"phone" gorm:"size:20"`
	OpenId     string    `json:"openId" gorm:"uniqueIndex;size:100"`
	UnionId    string    `json:"unionId" gorm:"size:100"`
	NickName   string    `json:"nickName" gorm:"size:100"`
	AvatarUrl  string    `json:"avatarUrl" gorm:"size:500"`
	Gender     int       `json:"gender" gorm:"default:0"` // 0:未知 1:男 2:女
	City       string    `json:"city" gorm:"size:50"`
	Province   string    `json:"province" gorm:"size:50"`
	Country    string    `json:"country" gorm:"size:50"`
	CreateTime time.Time `json:"createTime" gorm:"autoCreateTime"`
	UpdateTime time.Time `json:"updateTime" gorm:"autoUpdateTime"`
}

func (User) TableName() string {
	return "users"
}

type UserModel struct {
	db *gorm.DB
}

func NewUserModel(db *gorm.DB) *UserModel {
	return &UserModel{db: db}
}

func (m *UserModel) FindByUsername(username string) (*User, error) {
	var user User
	err := m.db.Where("username = ?", username).First(&user).Error
	return &user, err
}

func (m *UserModel) FindById(id int64) (*User, error) {
	var user User
	err := m.db.First(&user, id).Error
	return &user, err
}

func (m *UserModel) FindByOpenId(openId string) (*User, error) {
	var user User
	err := m.db.Where("open_id = ?", openId).First(&user).Error
	if err != nil {
		return nil, err
	}
	return &user, nil
}

func (m *UserModel) Create(user *User) error {
	return m.db.Create(user).Error
}

func (m *UserModel) Update(user *User) error {
	return m.db.Save(user).Error
}